package com.guoxin.part4.chapter17;

/**
 * @author guoxin
 * @date 2019/8/30
 */
class ReadLock implements Lock {
    private final ReadWriteLockImpl readWriteLock;

    ReadLock(ReadWriteLockImpl readWriteLock) {
        this.readWriteLock = readWriteLock;
    }

    @Override public void lock() throws InterruptedException {
        // 若此时有线程在进行写操作，或者有线程在等待并且偏向锁的标识为true时，
        // 就会无法获得锁，只能被挂起
        synchronized (readWriteLock.getMutex()) {
            while (readWriteLock.getWritingWriters() > 0 ||
                    (readWriteLock.getPreferWriter() &&
                            readWriteLock.getWaitingWriters() > 0)) {
                readWriteLock.getMutex().wait();
            }
            readWriteLock.incrementReadingReaders();
        }
    }

    @Override public void unlock() {
        synchronized (readWriteLock.getMutex()) {
            readWriteLock.decrementReadingReaders();
            readWriteLock.changePrefer(true);
            readWriteLock.getMutex().notifyAll();
        }
    }
}
